<template>
  <el-dialog :model-value="props.modelValue" title="推荐设置" width="70%" :before-close="dataFn.closePopup">
    <el-form :model="data" class="demo-form-inline" label-width="140px">

	  <el-form-item label="推荐标题" prop="title">
		<el-input v-model="data.post.title" :controls="false" placeholder="请输入标题" :maxlength="255"></el-input>
      </el-form-item>
      <el-form-item label="注册成功奖励数量" prop="registrationAward">
        <el-input-number v-model="data.post.registrationAward" :controls="false" placeholder="输入数量" :min="0"></el-input-number>
        <span class="isHint">小饼干</span>
      </el-form-item>
      <el-form-item label="最终成功奖励" prop="successAward">
        <el-input-number v-model="data.post.successAward" :controls="false" placeholder="输入数量" :min="0"></el-input-number>
        <span class="isHint">小饼干</span>
      </el-form-item>
      <el-form-item label="规则" prop="rule">
        <el-input v-model="data.post.rule" type="textarea" :maxlength="1000" :rows="4" placeholder="输入规则"></el-input>
      </el-form-item>

      <el-form-item label="累计奖励" prop="accumulatedRewards">
        <el-button type="primary" :disabled="data.post.accumulatedRewards.length>=5" plain @click="addEditFn.openPopup(null)">添加奖励</el-button>
        <el-table :data="data.post.accumulatedRewards" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;margin-top: 12px;" border>
          
          <el-table-column prop="successTimes" label="获取条件">
            <template #default="{row}">
            领取{{row.successTimes}}次最终奖励
            </template>
          </el-table-column>
          
          <el-table-column prop="reward" label="奖励数量(小饼干)" />
          
          <el-table-column fixed="right" label="操作" width="180px" align="center">
            <template #default="{row,$index}">
              <el-button size="small" type="primary" plain @click="addEditFn.openPopup(row,$index)">编辑</el-button>
              <el-button size="small" type="danger" plain @click = "dataFn.deletePre(row,$index)">{{row.deletedAt?"已删除":"删除"}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dataFn.closePopup">关闭</el-button>
        <el-button type="primary" @click="dataFn.savePre">保存</el-button>
      </div>
    </template>
    
    <el-dialog v-model="addEdit.showBox" width="50%" title="添加累计奖励" append-to-body :before-close="addEditFn.closePopup">
      
      <el-form :model="addEdit.post" class="demo-form-inline" label-width="120px">

        <el-form-item label="领取条件">
          <span class="isHint">领取最终奖励次数</span>
          <el-input-number v-model="addEdit.post.successTimes" :controls="false" placeholder="输入次数"></el-input-number>
        </el-form-item>
        <el-form-item label="奖励数量(小饼干)">
          <el-input-number v-model="addEdit.post.reward" :controls="false" placeholder="输入数量"></el-input-number>
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditFn.closePopup">关闭</el-button>
          <el-button type="primary" @click="addEditFn.addEditPre">保存</el-button>
        </div>
      </template>

    </el-dialog>
  </el-dialog>
  
</template>

<script setup>
import { reactive, watch } from "vue";
import {getInviteConfigDetail,setInviteConfig} from "@/api/invite";
import {parseTime} from "@/utils/index"
import { ElMessageBox,ElMessage } from "element-plus";

const props = defineProps({
  modelValue: Boolean,
});
const emit = defineEmits(["update:modelValue"]);

watch(()=> props.modelValue,(nv,ov)=>{
  console.log("new:",nv);
  if(nv===true){
    dataFn.getDetails();
  }
})

// 数据详情模块，包括 查看详情，大图预览
const {$data: data,$fn: dataFn} = (()=>{
  const $data = reactive({
    post:{
	  title: "",
      registrationAward: undefined,
      successAward: undefined,
      rule: "",
      accumulatedRewards: [],
    },
    deleteItems: [],
  })
  const $fn = {
    getDetails(){
      getInviteConfigDetail().then(res=>{
        if(res.code===0){
          $data.post = res.data||{};
          $data.post.accumulatedRewards = res.data.accumulatedRewards.map(item=>({
            id: item.id,
			title: item.title,
            reward: item.reward*1,
            successTimes: item.successTimes,
          }))
        }
      })
    },
    closePopup() {
      emit("update:modelValue", false);
      $data.deleteItems = [];
    },
    deletePre(row,index){
      ElMessageBox.confirm("是否删除该数据？", "提示", {
        type: "warning",
      }).then(() => {
        $fn.deleteData(row.id,index);
      });
    },
    deleteData(id,index){
      console.log("delete:",index);
      if(id){//删除（已存入库的数据）
        $data.deleteItems.push({
          ...$data.post.accumulatedRewards[index],
          deletedAt: parseTime(new Date()),
        })
      } 
      $data.post.accumulatedRewards.splice(index,1);
    },
    savePre(){
      if(!$data.post.rule){
        ElMessage.warning("请输入规则！");
        return;
      }
      $fn.saveData();
    },
    saveData(){
      let req = {
        ...$data.post,
        accumulatedRewards: [
          ...$data.post.accumulatedRewards,
          ...$data.deleteItems,
        ]
      }
      console.log("req:",req);
      setInviteConfig(req).then(res=>{
        if(res.code===0){
          ElMessage.success("保存成功！");
          $fn.closePopup();
        }
      })
    }
  }
  return {
    $data,
    $fn,
  }
})();

const {$data: addEdit,$fn: addEditFn} = (()=>{
  const backup ={
    post:{
      // id:"", //	修改和删除时传递（删除需要传递原数据传递）	
      successTimes: undefined, //	邀请成功数	
      reward:undefined, //	奖励
      // deletedAt:"", //	删除时间
    }
  }
  const $data = reactive({
    showBox: false,
    editIndex: null,
    post:{...backup.post},
  })
  const $fn = {
    openPopup(row,index){
      console.log("row,index",row,index);
      if(row){
        $data.post = {...row};
        $data.editIndex = index;
      }
      $data.showBox = true;
    },
    closePopup(){
      $data.showBox = false;
      $data.post = {...backup.post};
      $data.editIndex = null;
    },
    addEditPre(){
      if($data.post.successTimes===undefined || $data.post.reward===undefined){
        ElMessage.warning("请完善内容后再提交！");
        return;
      }
      $fn.addEditData();
    },
    addEditData(){
      console.log($data.editIndex,"post:",data.post);
      if($data.editIndex!==null){//编辑
        data.post.accumulatedRewards.splice($data.editIndex,1,{...$data.post});
      }else {//新增
        data.post.accumulatedRewards.push($data.post);
      }
      $fn.closePopup();
    }
  }
  return {
    $data,
    $fn,
  }
})();

</script>

<style scoped lang="scss">
  .isHint{
    color: #a0a0a0;
    margin: 0 8px;
  }
</style>